package cn.harry.modular.monitor.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.sys.domain.SysUserLoginLog;
import cn.harry.modular.sys.service.SysUserLoginLogService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: SysLoginLogController Description: 用户登陆日志
 *
 * @author honghh Date 2020/04/28 11:09 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "monitor-loginLog => 用户登陆日志")
@RequestMapping("/monitor/loginLog")
public class SysLoginLogController {

    private final SysUserLoginLogService sysUserLoginLogService;

    @Operation(summary = "list 分页列表")
    @GetMapping(value = "/list")
    public R<IPage<SysUserLoginLog>> list(Page<SysUserLoginLog> page,
                                          SysUserLoginLog loginLog) {
        return R.success(sysUserLoginLogService.page(page, Wrappers.lambdaQuery(loginLog)
                .orderByDesc(SysUserLoginLog::getCreateTime)));
    }

    @Operation(summary = "删除")
    @SysLog(title = "登陆日志", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        boolean count = sysUserLoginLogService.removeBatchByIds(Arrays.asList(ids));
        return count ? R.success() : R.failed();
    }

    @Operation(summary = "clean 清空记录")
    @SysLog(title = "登陆日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public R<Integer> clean() {
        sysUserLoginLogService.clean();
        return R.success();
    }

    @Operation(summary = "export 导出")
    @SysLog(title = "登陆日志", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(HttpServletResponse response, SysUserLoginLog loginLog) {
        List<SysUserLoginLog> list = sysUserLoginLogService.getExportList(loginLog);
        try {
            EasyExcel.write(response.getOutputStream(), SysUserLoginLog.class)
                    .sheet("登陆日志").doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("导出失败 error:{}", e.getMessage());
        }
        return R.failed();

    }

}
